package com.hqyj.shop.controller;


import com.hqyj.shop.pojo.Cart;
import com.hqyj.shop.service.imp.CartServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user/shop")
public class CartController {
    @Autowired
    private CartServiceImpl cartService;

    //添加商品到购物车
    @RequestMapping("/addCart")
    @ResponseBody
    public Map<String,Object> addCartOneGoods(String userId, String goodsId){
        Integer userIdin = Integer.parseInt(userId);
        Integer goodsIdin = Integer.parseInt(goodsId);
        boolean b=cartService.addCartOne(userIdin,goodsIdin);
        Map<String,Object> result =new HashMap<>();
        result.put("message","加入购物车成功");
        return result;
    }


    //显示购物车页面
    @RequestMapping("/cart")
    public String queryCart(String username, ModelMap modelMap){
        List<Cart> carts = cartService.queryCartByName(username);
        modelMap.put("carts",carts);
        System.out.println(carts);
        return "shop_cart";
    }

    //从购物车删除一个商品
    @RequestMapping("/deleteOneOnCart")
    public String deleteOneOnCart(Integer cartId,String username){
        //System.out.println(cartId);
        boolean b=cartService.deleteOneOnCart(cartId);

        return "redirect:/user/shop/cart?username="+username;
    }
    //添加和减少购物车商品数量
    @RequestMapping("/updateNum")
    //@ResponseBody
    public  String updateOneGoodsNum(Integer cartId,String addAndSub,Integer number,String username){
        if(number==1&&addAndSub.equals("sub")){
            cartService.deleteOneOnCart(cartId);
            return "redirect:/user/shop/cart?username="+username;
        }else {
            if(addAndSub.equals("add")){
                number+=1;
            }else {
                number-=1;
            }
            cartService.updateOneGoodsNum(cartId,number);
        }
        return "redirect:/user/shop/cart?username="+username;


    }
    //批量删除
    @RequestMapping("/deleteAll")
    public String deletAll(String[] ids,String[] username) {
        if (ids != null) {
            for (String id : ids) {
                int i = Integer.parseInt(id);
                cartService.deleteOneOnCart(i);
            }
        }
        return "redirect:/user/shop/cart?username="+username[0];
    }



}
